package com.example.demo.controller;

import com.example.demo.model.common.ApiResult;
import com.example.demo.model.dto.SubscriptionRequestDto;
import com.example.demo.model.entity.SubscriptionEntity;
import com.example.demo.service.SubscriptionService;
import com.example.demo.service.WechatMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/wechat/subscription")
@CrossOrigin
@Validated
public class WechatSubscriptionController {
    private static final Logger log = LoggerFactory.getLogger(WechatSubscriptionController.class);

    private final WechatMessageService wechatMessageService;
    private final SubscriptionService subscriptionService;

    // 使用构造函数注入替代@Autowired
    public WechatSubscriptionController(WechatMessageService wechatMessageService,
                                        SubscriptionService subscriptionService) {
        this.wechatMessageService = wechatMessageService;
        this.subscriptionService = subscriptionService;
    }

    @PostMapping("/subscribe")
    @Transactional
    public ResponseEntity<ApiResult<String>> subscribe(@Valid @RequestBody SubscriptionRequestDto request) {
        String openId = request.getOpenId();
        String deviceId = request.getDeviceId();

        // 遮盖部分敏感信息用于日志
        String maskedOpenId = maskSensitiveInfo(openId);
        log.info("开始处理订阅请求 - OpenId: {}, DeviceId: {}", maskedOpenId, deviceId);

        try {
            // 查询现有订阅信息
            log.debug("查询现有订阅信息");
            SubscriptionEntity subscription = subscriptionService.findByOpenIdAndDeviceId(openId, deviceId);
            if (subscription == null) {
                log.info("未找到现有订阅，创建新订阅");
                subscription = new SubscriptionEntity();
            } else {
                log.info("找到现有订阅，ID: {}, 当前状态: {}", subscription.getId(), subscription.getSubscribed());
            }

            // 更新或创建订阅信息
            subscription.setOpenId(openId);
            subscription.setDeviceId(deviceId);
            subscription.setSubscribed(true);
            subscription.setSubscribeTime(LocalDateTime.now());
            subscription.setExpireTime(LocalDateTime.now().plusDays(7));

            // 保存到数据库
            subscriptionService.saveOrUpdate(subscription);
            log.info("订阅信息保存成功，ID: {}", subscription.getId());

            return ResponseEntity.ok(ApiResult.success("订阅成功"));
        } catch (Exception e) {
            log.error("订阅处理过程中发生错误", e);
            return ResponseEntity.badRequest().body(ApiResult.error("订阅失败: " + e.getMessage()));
        }
    }

    @PostMapping("/unsubscribe")
    @Transactional
    public ResponseEntity<ApiResult<String>> unsubscribe(@Valid @RequestBody SubscriptionRequestDto request) {
        String openId = request.getOpenId();
        String deviceId = request.getDeviceId();

        String maskedOpenId = maskSensitiveInfo(openId);
        log.info("开始处理取消订阅请求 - OpenId: {}, DeviceId: {}", maskedOpenId, deviceId);

        try {
            // 查找订阅信息
            SubscriptionEntity subscription = subscriptionService.findByOpenIdAndDeviceId(openId, deviceId);
            if (subscription == null) {
                log.warn("未找到订阅信息");
                // 返回成功但提示用户未订阅，而不是抛出异常
                return ResponseEntity.ok(ApiResult.success("未找到订阅信息，无需取消"));
            }

            log.info("找到订阅信息，ID: {}", subscription.getId());

            // 更新订阅状态
            subscription.setSubscribed(false);
            subscriptionService.updateById(subscription);
            log.info("成功更新订阅状态为未订阅");

            return ResponseEntity.ok(ApiResult.success("取消订阅成功"));
        } catch (Exception e) {
            log.error("取消订阅过程中发生错误", e);
            return ResponseEntity.badRequest().body(ApiResult.error("取消订阅失败: " + e.getMessage()));
        }
    }

    @GetMapping("/check")
    public ResponseEntity<ApiResult<Boolean>> checkSubscription(@RequestParam String openId,
                                                                @RequestParam String deviceId) {
        String maskedOpenId = maskSensitiveInfo(openId);
        log.info("开始检查订阅状态 - OpenId: {}, DeviceId: {}", maskedOpenId, deviceId);

        try {
            // 查询订阅信息
            SubscriptionEntity subscription = subscriptionService.findByOpenIdAndDeviceId(openId, deviceId);

            // 检查订阅状态和过期时间
            boolean isSubscribed = isValidSubscription(subscription);
            log.info("订阅状态查询结果: {}", isSubscribed);

            return ResponseEntity.ok(ApiResult.success(isSubscribed));
        } catch (Exception e) {
            log.error("检查订阅状态过程中发生错误", e);
            return ResponseEntity.badRequest().body(ApiResult.error("查询订阅状态失败"));
        }
    }

    /**
     * 检查订阅是否有效（已订阅且未过期）
     */
    private boolean isValidSubscription(SubscriptionEntity subscription) {
        if (subscription == null || !subscription.getSubscribed()) {
            return false;
        }

        // 检查过期时间
        LocalDateTime now = LocalDateTime.now();
        return subscription.getExpireTime() != null && now.isBefore(subscription.getExpireTime());
    }

    /**
     * 遮盖敏感信息用于日志记录
     */
    private String maskSensitiveInfo(String info) {
        if (info == null || info.length() <= 8) {
            return "***";
        }
        int visibleChars = 4;
        return info.substring(0, visibleChars) + "***" +
                info.substring(info.length() - visibleChars);
    }
}